package com.ysxsoft.wdg.ui.activity.center_st;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.exoplayer2.source.BehindLiveWindowException;
import com.umeng.socialize.UMShareAPI;
import com.youth.banner.Banner;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.DiscussBean;
import com.ysxsoft.wdg.bean.DiscussBean2;
import com.ysxsoft.wdg.bean.st.StGoodsBean;
import com.ysxsoft.wdg.bean.st.StProductBean;
import com.ysxsoft.wdg.bean.zy.GoodsBean;
import com.ysxsoft.wdg.bean.zy.GoodsRulesBean;
import com.ysxsoft.wdg.bean.zy.ZyGoodsBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsPlActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsRulesActivity;
import com.ysxsoft.wdg.ui.activity.login.LoginValid;
import com.ysxsoft.wdg.util.BigDecimalUtil;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.WebViewUtils;
import com.ysxsoft.wdg.util.delayaction.Action;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.SharePopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class StGoodsDetailActivity extends BaseActivity {


    private GoodsBean productBean;

    public static void start(Context context, String productid) {
        Intent intent = new Intent(context, StGoodsDetailActivity.class);
        intent.putExtra("productid", productid);
        context.startActivity(intent);
    }


    @BindView(R.id.banner)
    ImageView banner;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sold)
    TextView tvSold;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.iv_del)
    ImageView ivDel;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.ll_2_pl)
    LinearLayout ll2Pl;
    @BindView(R.id.iv_pl_tx)
    ImageView ivPlTx;
    @BindView(R.id.tv_pl_nick)
    TextView tvPlNick;
    @BindView(R.id.tv_pl_content)
    TextView tvPlContent;
    @BindView(R.id.ll_pl_1)
    LinearLayout llPl1;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.btn_share)
    ImageView btnShare;
    @BindView(R.id.btn_cart)
    ImageView btnCart;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.tv_money_all)
    TextView tvMoneyAll;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.all)
    TextView all;

    private String uid = "", productid = "";
    private int num = 1;
    int store=2;
    private String onePrice = "", totalPrice = "";
    private UMShareAPI mShareAPI;
    private SharePopupWindow popupWindow;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tvNum.setText(num + "");
                    totalPrice = BigDecimalUtil.formatDoubleScale(BigDecimalUtil.mul(Double.parseDouble(onePrice), num));
                    tvMoneyAll.setText(getString(R.string.price_rmb, totalPrice));
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop_detail2;
    }

    private String companyid = "";

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        btnCart.setVisibility(View.GONE);
        WebViewUtils.init(webView);

        uid = SharePrefUtils.getUserId();
        productid = getIntent().getStringExtra("productid");
        mShareAPI = UMShareAPI.get(this);
        popupWindow = new SharePopupWindow(this, mShareAPI);

        mApiHelper.getZyGoodsdetail(uid,productid, new Observer<BaseBean<ZyGoodsBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<ZyGoodsBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    ZyGoodsBean bean = baseBean.getData();
                    productBean = bean.getGoods();

                    ViewUtils.loadImage(mContext, productBean.getPic(), banner);
                    productPic=productBean.getPic();//商品图片

                    tvName.setText(productBean.getName());
                    tvSold.setText("销量" + productBean.getSold());
                    onePrice = productBean.getPrice();
                    tvMoney.setText(getString(R.string.price_rmb, onePrice));
//                    tvContent.setText(productBean.getDesrc());

                    WebViewUtils.setData(webView,productBean.getDetail());//商品简介
                    store = Integer.parseInt(productBean.getStore());//TODO:是否会返回
                    totalPrice = onePrice;
                    handler.sendEmptyMessage(0);

                    companyid = productBean.getCompanyid();
                    List<DiscussBean2> discuss = bean.getDiscuss();
                    if (discuss.size() == 0) {
                        llPl1.setVisibility(View.GONE);
                    } else {
                        llPl1.setVisibility(View.VISIBLE);
                        DiscussBean2 discussBean = discuss.get(0);
                        tvPlNick.setText(discussBean.getNickname());
                        tvPlContent.setText(discussBean.getContent());
                        ViewUtils.loadCircleImage(mContext, discussBean.getAvatar(), ivPlTx);
                    }
                    id = productBean.getId();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private String id;

    @Override
    protected void setListener() {

    }

    @OnClick({R.id.btn_finish, R.id.tv_buy, R.id.iv_del,
            R.id.iv_add, R.id.ll_2_pl, R.id.btn_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.tv_buy:
//                SingleCall.getInstance().addAction(new Action() {
//                    @Override
//                    public void call() {
//                        //实体确认订单
//                        StGoodsConfirmActivity.start(mContext, productBean.getName(), productid, onePrice, num, store, companyid);
//                    }
//                }).addValid(new LoginValid(this, 1)).doCall();
                getRules();
                break;
            case R.id.iv_del:
                if (num <= 1) {
                    return;
                }
                num--;
                handler.sendEmptyMessage(0);
                break;
            case R.id.iv_add:
                if (num >= store) {
                    ToastUtils.showToast("库存不足");
                    return;
                }
                num++;
                handler.sendEmptyMessage(0);
                break;
            case R.id.ll_2_pl:
                GoodsPlActivity.start(StGoodsDetailActivity.this, id,"1");
                break;
            case R.id.btn_share:
                popupWindow.setShareData(getString(R.string.app_name), "商品分享",UrlHost.BASE_URL+"/index.html#/details?store=1&id="+id, "", 0);
                popupWindow.show(mRootView);
                break;
        }
    }

    /**
     * 获取规格
     */
    private void getRules() {
        mApiHelper.getZyRules(productid, new Observer<BaseBean<GoodsRulesBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<GoodsRulesBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    GoodsBean product = baseBean.getData().getProduct();

                    Intent intent = new Intent(mContext, GoodsRulesActivity.class);
                    intent.putExtra("goodsBean", product);
                    intent.putExtra("isStGood",true);
                    intent.putExtra(GoodsRulesActivity.JUMP_CODE, "buy");//立即狗狗买
                    intent.putParcelableArrayListExtra("rules", (ArrayList<? extends Parcelable>) baseBean.getData().getRule());
                    startActivityForResult(intent,0x01);
                    overridePendingTransition(R.anim.slide_in_bottom, 0);
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private String productPic;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            switch (requestCode){
                case 0x01:
                    if(data!=null){
                        num=data.getIntExtra("buyNum",1);
                        String ruleId=data.getStringExtra("ruleId");
                        String priceOne=data.getStringExtra("priceOne");
                        String rules=data.getStringExtra("rules");

                        if(!"".equals(priceOne)){
                            onePrice=priceOne;//选择的单价
                        }else{
                            onePrice=productBean.getPrice();
                        }

                        SingleCall.getInstance().addAction(new Action() {
                            @Override
                            public void call() {
                                //实体确认订单
                                StGoodsConfirmActivity.start(StGoodsDetailActivity.this, productBean.getName(), productid, onePrice, num, store, companyid,ruleId,productPic,rules);
                            }
                        }).addValid(new LoginValid(this, 1)).doCall();
                    }
                    break;
            }
        }
    }
}
